// lib/views/person_chat_screen.dart
import 'package:chat/controller/friend_chat_controller.dart';
import 'package:chat/model/message_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

final FriendChatController controller = Get.find();

var safeAreaFlag = false;
const iphoneHeights = [812, 844, 852, 896, 926, 932];

class FriendChatScreen extends StatefulWidget {
  const FriendChatScreen({super.key});

  @override
  _FriendChatScreenState createState() => _FriendChatScreenState();
}

class _FriendChatScreenState extends State<FriendChatScreen> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    debugPrint('dispose');
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    final double newHeight =
        WidgetsBinding.instance.window.viewInsets.bottom /
        WidgetsBinding.instance.window.devicePixelRatio;
    //if (mounted) {
    debugPrint('newHeight: $newHeight');
    if (newHeight > controller.keyboardHeight.value) {
      controller.keyboardHeight.value = newHeight;
    }
    if ((controller.showImg.value || controller.showOptions.value) &&
        !controller.textFieldFocusNode.hasFocus) {
      controller.keyboardHeight.value = 260.0;
    }
    //controller.scrollToBottom();
    debugPrint('keyboardHeight: ${controller.keyboardHeight}');
    //}
  }

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    debugPrint('screenHeight: $screenHeight');
    if (iphoneHeights.contains(screenHeight.round())) {
      safeAreaFlag = true;
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      controller.scrollToBottom();
    });
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Obx(
          () => Text(
            controller.currentContact.value,
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
        foregroundColor: Colors.black,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () {
            Navigator.of(context).pop();
            controller.toggleAll();
          },
        ),
        actions: [
          PopupMenuButton<String>(
            position: PopupMenuPosition.under,
            color: Colors.white,
            offset: Offset(5, 0),
            icon: Icon(Icons.more_vert, color: Colors.grey),
            itemBuilder:
                (BuildContext context) => <PopupMenuEntry<String>>[
                  PopupMenuItem<String>(value: 'option1', child: Text('选项1')),
                  PopupMenuItem<String>(value: 'option2', child: Text('选项2')),
                  PopupMenuItem<String>(value: 'option3', child: Text('选项3')),
                ],
            onSelected: (String value) {
              // 处理菜单项选择
              switch (value) {
                case 'option1':
                  break;
                case 'option2':
                  break;
                case 'option3':
                  break;
              }
            },
          ),
        ],
      ),
      body: Obx(
        () => Padding(
          padding:
              controller.showPadding.value
                  ? EdgeInsets.only(bottom: safeAreaFlag ? 20 : 0)
                  : EdgeInsets.zero,
          child: Column(
            children: [
              Expanded(
                child: Obx(
                  () => ListView.builder(
                    controller: controller.scrollController,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    itemCount: controller.messages.length,
                    itemBuilder: (context, index) {
                      final message = controller.messages.toList()[index];
                      return _buildMessageBubble(message);
                    },
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: [
                    _buildInputButton(Icons.mic, () {}),
                    SizedBox(width: 10),
                    Expanded(
                      child: TextField(
                        controller: controller.messageController,
                        focusNode: controller.textFieldFocusNode,
                        decoration: InputDecoration(
                          hintText: 'Message',
                          hintStyle: TextStyle(fontSize: 14, color: Colors.grey[500]),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(20),
                            borderSide: BorderSide.none,
                          ),
                          filled: true,
                          fillColor: Color(0xFFF5F6F7),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 10,
                          ), // 关键调整
                          isDense: true, // 关键参数，减少内部高度
                        ),
                        style: TextStyle(fontSize: 14), // 可选：调小字体
                        onSubmitted: (_) => controller.sendMessage(),
                      ),
                    ),
                    SizedBox(width: 10),
                    _buildInputButton(Icons.image, () {
                      controller.toggleImg();
                    }),
                    SizedBox(width: 10),
                    _buildInputButton(Icons.add, () {
                      controller.toggleOptions();
                    }),
                  ],
                ),
              ),
              Obx(() => controller.showOther.value ? _buildOther() : const SizedBox()),
              Obx(() => controller.showImg.value ? _buildImg() : const SizedBox()),
              Obx(() => controller.showOptions.value ? _buildOptions() : const SizedBox()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMessageBubble(Message message) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        mainAxisAlignment: message.isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        //crossAxisAlignment: CrossAxisAlignment.end, // 使头像和消息底部对齐
        children: [
          if (!message.isMe) // 对方消息显示头像
            Padding(
              padding: const EdgeInsets.only(right: 8),
              child: CircleAvatar(
                backgroundImage: AssetImage('assets/images/zh-CN-XiaochenNeural.png'),
                radius: 16, // 稍微缩小头像
              ),
            ),
          // 消息内容区域
          Flexible(
            // 关键：使用Flexible确保宽度自适应
            child: Column(
              crossAxisAlignment: message.isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                  decoration: BoxDecoration(
                    color: message.isMe ? Color(0xFFE1F166) : Color(0xFFF5F6F7),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Text(
                    message.content,
                    style: const TextStyle(fontSize: 16),
                    softWrap: true,
                  ),
                ),
              ],
            ),
          ),
          if (message.isMe) // 消息是我
            Padding(
              padding: const EdgeInsets.only(left: 8),
              child: CircleAvatar(
                backgroundImage: AssetImage('assets/images/zh-CN-XiaohanNeural.png'),
                radius: 16,
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildInputButton(IconData icon, VoidCallback onTap) {
    return Container(
      width: 40,
      height: 40,
      alignment: Alignment.center,
      decoration: BoxDecoration(color: Color(0xFFF5F6F7), shape: BoxShape.circle),
      child: IconButton(icon: Icon(icon, size: 16), onPressed: onTap),
    );
  }

  Widget _buildOther() {
    return Obx(
      () => Container(
        height: controller.keyboardHeight.value,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      ),
    );
  }

  Widget _buildImg() {
    return Obx(
      () => Container(
        height: controller.keyboardHeight.value,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: SingleChildScrollView(
          child: Wrap(
            spacing: 2.0,
            runSpacing: 2.0,
            alignment: WrapAlignment.start,
            children:
                controller.emojis.map((emoji) {
                  return GestureDetector(
                    onTap: () {
                      debugPrint('Selected emoji: $emoji');
                    },
                    child: Container(
                      padding: EdgeInsets.all(2),
                      child: Text(emoji, style: TextStyle(fontSize: 24)),
                    ),
                  );
                }).toList(),
          ),
        ),
      ),
    );
  }

  Widget _buildOptions() {
    return Obx(
      () => Container(
        height: controller.keyboardHeight.value,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildOptionButton(
                  Icons.photo,
                  '照片',
                  () => controller.sendMedia(MessageType.image),
                ),
                SizedBox(width: 20),
                _buildOptionButton(
                  Icons.videocam,
                  '小视频',
                  () => controller.sendMedia(MessageType.video),
                ),
                SizedBox(width: 20),
                _buildOptionButton(
                  Icons.location_on,
                  '位置',
                  () => controller.sendMedia(MessageType.location),
                ),
                SizedBox(width: 20),
                _buildOptionButton(Icons.call, '语音通话', () {}),
              ],
            ),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildOptionButton(Icons.video_call, '视频通话', () {}),
                SizedBox(width: 20),
                _buildOptionButton(
                  Icons.keyboard_voice,
                  '语音输入',
                  () => controller.sendMedia(MessageType.voice),
                ),
                SizedBox(width: 20),
                SizedBox(width: 70),
                SizedBox(width: 20),
                SizedBox(width: 70),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOptionButton(IconData icon, String label, VoidCallback onTap) {
    return Column(
      children: [
        Container(
          width: 70,
          height: 70,
          decoration: BoxDecoration(
            color: Color(0xFFF5F6F7),
            borderRadius: BorderRadius.circular(16),
          ),
          child: IconButton(icon: Icon(icon), onPressed: onTap),
        ),
        const SizedBox(height: 4),
        Text(label, style: const TextStyle(fontSize: 10)),
      ],
    );
  }
}
